import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
// import QtQuick.Effects  // 暂时不使用MultiEffect，兼容性问题

Rectangle {
    id: skillTreePage
    
    // 天空渐变背景 - 美化版
    gradient: Gradient {
        GradientStop { position: 0.0; color: "#87CEEB" }  // 天空蓝
        GradientStop { position: 0.5; color: "#B0E2FF" }
        GradientStop { position: 1.0; color: "#E0F6FF" }  // 浅蓝
    }
    
    // 漂浮的云朵装饰
    Repeater {
        model: 6
        
        Text {
            text: "☁️"
            font.pixelSize: 40 + Math.random() * 40
            opacity: 0.3
            x: Math.random() * skillTreePage.width
            y: Math.random() * 400
            z: -1  // 放在最底层
            
            SequentialAnimation on x {
                loops: Animation.Infinite
                NumberAnimation {
                    from: -100
                    to: skillTreePage.width + 100
                    duration: 30000 + Math.random() * 20000
                }
            }
        }
    }
    
    // 删除模式状态
    property bool deleteMode: false
    
    // 定位到根节点的函数（可复用）
    function positionToRootNode() {
        Qt.callLater(function() {
            if (skillModel.count > 0) {
                // 查找根节点（parent === -1）并定位到根节点位置
                var rootX = 0
                var rootY = 0
                var foundRoot = false
                
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    if (skill.parent === -1) {
                        // 找到根节点，使用第一个根节点的位置
                        rootX = (skill.x + treeCanvas.xOffset) + 30 // 30是技能节点半径（节点中心）
                        rootY = (skill.y + treeCanvas.yOffset) + 60 // 60是节点高度（节点底部边缘）
                        foundRoot = true
                        break // 只定位到第一个根节点
                    }
                }
                
                if (foundRoot) {
                    // 设置滚动位置，使根节点在屏幕底部中间
                    var maxScrollX = Math.max(0, flickable.contentWidth - flickable.width)
                    var maxScrollY = Math.max(0, flickable.contentHeight - flickable.height)
                    
                    // 水平定位：根节点偏右
                    flickable.contentX = Math.min(Math.max(0, rootX - flickable.width / 2 + 150), maxScrollX)
                    
                    // 垂直定位：根节点底部距离屏幕底部的距离
                    var targetY = rootY - flickable.height + 180 // 180是根节点底部到屏幕底部的距离
                    flickable.contentY = Math.min(Math.max(0, targetY), maxScrollY)
                }
            }
        })
    }

    Component.onCompleted: {
        // 初次加载时，延迟定位到根节点（底部水平居中）
        positionToRootNode()
        
        // 刷新技能树列表
        treeSelector.model = skillModel.getSkillTrees()
        
        // 注意：不在这里调用 checkAndSyncOnStartup()
        // 因为在 setCloudSyncConfig 时已经调用过了
    }
    
    // 注意：不使用 Component.onDestruction
    // 因为在 AppMain.qml 的 Loader.onActiveChanged 中已经调用了
    
    // 监听技能树切换事件，自动定位到新技能树的根节点
    Connections {
        target: skillModel
        function onCurrentTreeIdChanged() {
            // 技能树切换时，自动定位到根节点
            positionToRootNode()
        }
        
        // 监听技能树数量变化，刷新下拉框
        function onCountChanged() {
            treeSelector.model = skillModel.getSkillTrees()
            if (treeSelector.model.length > 0 && treeSelector.currentIndex < 0) {
                treeSelector.currentIndex = 0
            }
        }
        
        // 注意：云同步冲突信号在 AppMain.qml 中处理
        // 因为当离开界面时，这个组件可能已经被卸载
    }

    // 缩放指示器
    Rectangle {
        id: zoomIndicator
        anchors.bottom: parent.bottom
        anchors.right: parent.right
        anchors.margins: 20
        width: 120
        height: 40
        radius: 20
        color: "#80000000"
        border.color: "#4ECDC4"
        border.width: 2
        z: 1000
        
        Text {
            anchors.centerIn: parent
            text: "🔍 " + Math.round(treeCanvas.scale * 100) + "%"
            color: "white"
            font.pixelSize: 14
            font.bold: true
        }
        
        // 自动隐藏
        opacity: zoomIndicatorTimer.running ? 1.0 : 0.0
        
        Behavior on opacity {
            NumberAnimation {
                duration: 300
            }
        }
        
        Timer {
            id: zoomIndicatorTimer
            interval: 1500
            running: false
            repeat: false
        }
    }
    
    // 缩放操作提示（初次进入显示）
    Rectangle {
        id: zoomHint
        anchors.top: controlBar.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 10
        width: hintText.width + 30
        height: 35
        radius: 17
        color: "#E0FFD700"
        border.color: "#FFD700"
        border.width: 2
        z: 999
        
        // 5秒后自动隐藏
        opacity: 1.0
        visible: opacity > 0
        
        Text {
            id: hintText
            anchors.centerIn: parent
            text: "💡 提示：按住Ctrl+滚轮可缩放视图"
            color: "#8B4513"
            font.pixelSize: 13
            font.bold: true
        }
        
        Timer {
            interval: 5000
            running: true
            onTriggered: {
                zoomHint.opacity = 0
            }
        }
        
        Behavior on opacity {
            NumberAnimation {
                duration: 500
            }
        }
        
        // 点击关闭提示
        MouseArea {
            anchors.fill: parent
            onClicked: {
                zoomHint.opacity = 0
            }
        }
    }
    
    // 顶部控制栏 - 美化版
    Rectangle {
        id: controlBar
        width: parent.width
        height: 100
        
        // 彩虹渐变背景
        gradient: Gradient {
            orientation: Gradient.Horizontal
            GradientStop { position: 0.0; color: "#FF6B9D" }
            GradientStop { position: 0.3; color: "#C44569" }
            GradientStop { position: 0.6; color: "#FFA07A" }
            GradientStop { position: 1.0; color: "#FFD700" }
        }
        
        // 简单阴影效果（兼容性更好）
        Rectangle {
            anchors.fill: parent
            anchors.topMargin: 4
            color: "#20000000"
            radius: parent.radius
            z: -1
        }
        
        RowLayout {
            anchors.fill: parent
            anchors.margins: 15
            spacing: 15

            // 技能树切换下拉框（支持双击/长按重命名）
            Item {
                Layout.preferredWidth: 250
                Layout.preferredHeight: 50
                
                ComboBox {
                    id: treeSelector
                    anchors.fill: parent
                    font.pixelSize: 16
                    font.bold: true
                    
                    // 使用 C++ 模型中的 getSkillTrees 方法获取数据
                    model: skillModel.getSkillTrees()
                    textRole: "name" // 显示技能树名称
                    valueRole: "id"  // 使用技能树ID作为实际值

                    background: Rectangle {
                        color: "white"
                        radius: 25
                        border.color: "#FF69B4"
                        border.width: 2
                        
                        // 左键单击/长按检测（用于打开下拉框和长按重命名）
                        MouseArea {
                            anchors.fill: parent
                            acceptedButtons: Qt.LeftButton
                            
                            // 长按计时器
                            property bool isLongPress: false
                            property int pressStartTime: 0
                            
                            Timer {
                                id: longPressTimer
                                interval: 800
                                running: false
                                repeat: false
                                onTriggered: {
                                    if (treeSelector.model.length > 0 && treeSelector.currentIndex >= 0) {
                                        var currentTree = treeSelector.model[treeSelector.currentIndex]
                                        showEditTreeDialog(currentTree.id, currentTree.name)
                                        parent.isLongPress = true
                                    }
                                }
                            }
                            
                            onPressed: {
                                pressStartTime = Date.now()
                                isLongPress = false
                                longPressTimer.start()
                            }
                            
                            onReleased: {
                                longPressTimer.stop()
                            }
                            
                            // 单击时让 ComboBox 正常打开
                            onClicked: {
                                if (!isLongPress) {
                                    treeSelector.popup.open()
                                }
                            }
                        }
                        
                        // 右键单击检测（用于重命名技能树）
                        MouseArea {
                            anchors.fill: parent
                            acceptedButtons: Qt.RightButton
                            
                            onClicked: {
                                if (mouse.button === Qt.RightButton) {
                                    if (treeSelector.model.length > 0 && treeSelector.currentIndex >= 0) {
                                        var currentTree = treeSelector.model[treeSelector.currentIndex]
                                        showEditTreeDialog(currentTree.id, currentTree.name)
                                    }
                                }
                            }
                        }
                    }

                    // 默认值
                    onActivated: {
                        skillModel.currentTreeId = model[currentIndex].id // 切换 C++ 模型的当前树ID
                    }

                    // 确保在模型加载后默认选中第一个
                    Component.onCompleted: {
                        if (model.length > 0) {
                            treeSelector.currentIndex = 0;
                            skillModel.currentTreeId = model[0].id;
                        }
                    }

                    // 监听 C++ 模型中的 currentTreeIdChanged 信号，确保 ComboBox 同步
                    Connections {
                        target: skillModel
                        function onCurrentTreeIdChanged() {
                            for(var i = 0; i < treeSelector.model.length; i++) {
                                if (treeSelector.model[i].id === skillModel.currentTreeId) {
                                    treeSelector.currentIndex = i;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            // 新增技能树按钮 - 美化版
            Button {
                Layout.preferredHeight: 60
                font.pixelSize: 18
                font.bold: true
                
                background: Rectangle {
                    radius: 30
                    gradient: Gradient {
                        GradientStop { position: 0.0; color: parent.pressed ? "#FF1493" : "#FF69B4" }
                        GradientStop { position: 1.0; color: parent.pressed ? "#FF69B4" : "#FFB6C1" }
                    }
                    
                    // 简单阴影（移除MultiEffect以提高兼容性）
                    Rectangle {
                        anchors.fill: parent
                        anchors.topMargin: 3
                        color: "#30FF69B4"
                        radius: parent.radius
                        z: -1
                    }
                }
                
                contentItem: Row {
                    spacing: 8
                    anchors.centerIn: parent
                    
                    Text {
                        text: "✨"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    Text {
                        text: "新建技能树"
                        color: "white"
                        font: parent.parent.font
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
                
                onClicked: {
                    var newId = skillModel.createNewSkillTree("新建技能树 " + (treeSelector.model.length + 1))
                    treeSelector.model = skillModel.getSkillTrees()
                    skillModel.currentTreeId = newId
                }
            }
            
            // 删除模式按钮 - 美化版
            Button {
                Layout.preferredHeight: 60
                font.pixelSize: 18
                font.bold: true
                
                background: Rectangle {
                    radius: 30
                    gradient: Gradient {
                        GradientStop { position: 0.0; color: parent.pressed ? "#FF4444" : "#FF6666" }
                        GradientStop { position: 1.0; color: parent.pressed ? "#FF6666" : "#FF8888" }
                    }
                    
                    // 简单阴影
                    Rectangle {
                        anchors.fill: parent
                        anchors.topMargin: 3
                        color: "#30FF6666"
                        radius: parent.radius
                        z: -1
                    }
                }
                
                contentItem: Row {
                    spacing: 8
                    anchors.centerIn: parent
                    
                    Text {
                        text: deleteMode ? "✅" : "🗑️"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    Text {
                        text: deleteMode ? "完成删除" : "删除节点"
                        color: "white"
                        font: parent.parent.font
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
                
                onClicked: {
                    deleteMode = !deleteMode
                    if (!deleteMode) {
                        stopAllShaking()
                    }
                }
            }
            
            // 删除技能树按钮 - 美化版
            Button {
                Layout.preferredHeight: 60
                font.pixelSize: 18
                font.bold: true
                
                background: Rectangle {
                    radius: 30
                    gradient: Gradient {
                        GradientStop { position: 0.0; color: parent.pressed ? "#CC0000" : "#FF3333" }
                        GradientStop { position: 1.0; color: parent.pressed ? "#FF3333" : "#FF5555" }
                    }
                    
                    // 简单阴影
                    Rectangle {
                        anchors.fill: parent
                        anchors.topMargin: 3
                        color: "#30FF3333"
                        radius: parent.radius
                        z: -1
                    }
                }
                
                contentItem: Row {
                    spacing: 8
                    anchors.centerIn: parent
                    
                    Text {
                        text: "🗑️"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    Text {
                        text: "删除技能树"
                        color: "white"
                        font: parent.parent.font
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
                
                onClicked: {
                    if (treeSelector.model.length > 1) {
                        var currentTreeName = treeSelector.model[treeSelector.currentIndex].name
                        showDeleteTreeConfirmDialog(skillModel.currentTreeId, currentTreeName)
                    } else {
                        showSingleTreeWarningDialog()
                    }
                }
            }
        }
    }
    
    // 云同步状态提示
    Rectangle {
        id: syncStatusBar
        anchors.top: controlBar.bottom
        anchors.right: parent.right
        anchors.rightMargin: 20
        anchors.topMargin: 15
        width: 200
        height: 50
        radius: 25
        z: 1000
        
        opacity: 0
        visible: opacity > 0
        
        property bool isSuccess: true
        
        color: isSuccess ? "#4CAF50" : "#FF6666"
        
        border.color: "white"
        border.width: 2
        
        Row {
            anchors.centerIn: parent
            spacing: 10
            
            Text {
                id: syncStatusIcon
                text: "☁️"
                font.pixelSize: 24
                anchors.verticalCenter: parent.verticalCenter
                
                SequentialAnimation on rotation {
                    running: syncStatusBar.opacity > 0
                    loops: Animation.Infinite
                    NumberAnimation { from: 0; to: 360; duration: 2000 }
                }
            }
            
            Text {
                id: syncStatusText
                text: "同步中..."
                font.pixelSize: 14
                font.bold: true
                color: "white"
                anchors.verticalCenter: parent.verticalCenter
            }
        }
        
        Behavior on opacity {
            NumberAnimation { duration: 300 }
        }
    }
    
    // 云同步信号连接
    Connections {
        target: skillModel
        
        function onSyncStarted() {
            syncStatusIcon.text = "☁️"
            syncStatusText.text = "同步中..."
            syncStatusBar.opacity = 1
        }
        
        function onSyncSuccess(message) {
            syncStatusIcon.text = "✅"
            syncStatusText.text = message
            syncStatusBar.isSuccess = true
            syncStatusBar.opacity = 1
            
            // 2秒后自动隐藏
            syncHideTimer.start()
        }
        
        function onSyncFailed(errorMsg) {
            syncStatusIcon.text = "❌"
            syncStatusText.text = "同步失败"
            syncStatusBar.isSuccess = false
            syncStatusBar.opacity = 1
            
            // 3秒后自动隐藏
            syncHideTimer.interval = 3000
            syncHideTimer.start()
        }
    }
    
    // 自动隐藏计时器
    Timer {
        id: syncHideTimer
        interval: 2000
        repeat: false
        onTriggered: {
            syncStatusBar.opacity = 0
            interval = 2000  // 重置为默认值
        }
    }

    // 云端上传按钮
    Rectangle {
        id: uploadButton
        anchors.top: controlBar.bottom
        anchors.right: parent.right
        anchors.topMargin: 30
        anchors.rightMargin: 20
        width: 50
        height: 50
        radius: 25
        z: 1000

        // 根据数据修改状态改变颜色
        color: skillModel.dataModified ? "green" : "gray"  // 绿色表示有修改，灰色表示未修改

        // 调试：显示当前状态
        Text {
            anchors.centerIn: parent
            text: skillModel.dataModified ? "M" : "U"  // M=Modified, U=Unmodified
            font.pixelSize: 12
            color: "white"
            font.bold: true
        }

        border.color: "white"
        border.width: 2

        // 暂时移除箭头图标，只显示调试状态
        // Text {
        //     anchors.centerIn: parent
        //     text: "⬆️"
        //     font.pixelSize: 24
        // }

        // 点击和悬停效果
        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            enabled: skillModel.dataModified  // 只有在有修改时才可点击

            onClicked: {
                if (skillModel.dataModified) {
                    skillModel.syncToCloud()
                }
            }

            onEntered: {
                if (skillModel.dataModified) {  // 只有在可点击状态下才有悬停效果
                    uploadButton.scale = 1.1
                }
            }

            onExited: {
                uploadButton.scale = 1.0
            }
        }

        // 缩放动画
        Behavior on scale {
            NumberAnimation {
                duration: 150
            }
        }

        // 颜色变化动画
        Behavior on color {
            ColorAnimation {
                duration: 300
            }
        }
    }

    // 技能树渲染区
    Flickable {
        id: flickable
        anchors.top: controlBar.bottom
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.rightMargin: 15  // 为滚动条留出空间
        anchors.bottomMargin: 15 // 为滚动条留出空间
        contentWidth: treeCanvas.width * treeCanvas.scale // 确保内容可滚动（考虑缩放）
        contentHeight: treeCanvas.height * treeCanvas.scale // 使用Canvas的实际高度（考虑缩放）
        clip: true
        flickableDirection: Flickable.HorizontalAndVerticalFlick
        boundsBehavior: Flickable.DragOverBounds // 允许轻微超出边界并回弹
        flickDeceleration: 1500
        interactive: true
        maximumFlickVelocity: 2500
        rebound: Transition {
            NumberAnimation {
                properties: "x,y"
                duration: 200
                easing.type: Easing.OutQuad
            }
        }
        
        // 优化触摸响应
        pressDelay: 0  // 立即响应触摸
        
        // 点击空白处关闭操作对话框
        MouseArea {
            anchors.fill: parent
            z: -1  // 放在最底层，让节点的MouseArea优先响应
            propagateComposedEvents: true  // 让滚动和缩放事件穿透
            
            onClicked: {
                // 点击空白处时，关闭技能操作对话框
                if (skillActionDialog.opened) {
                    skillActionDialog.close()
                }
            }
            
            // 让按下事件穿透，不影响拖动
            onPressed: function(mouse) {
                mouse.accepted = false
            }
        }
        
        // PC端：Ctrl+滚轮缩放功能（类似高德地图）
        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.NoButton  // 不接受鼠标点击，只处理滚轮
            propagateComposedEvents: true  // 让点击事件穿透
            hoverEnabled: true  // 启用鼠标悬停以获取鼠标位置
            
            onWheel: function(wheel) {
                // 只有按住Ctrl键时才进行缩放（类似高德地图、Google Maps）
                if (wheel.modifiers & Qt.ControlModifier) {
                    // 获取鼠标在Flickable视口中的位置
                    var mouseX = wheel.x
                    var mouseY = wheel.y
                    
                    // 计算鼠标位置对应的Canvas上的点（未缩放的原始坐标）
                    var canvasX = (flickable.contentX + mouseX) / treeCanvas.scale
                    var canvasY = (flickable.contentY + mouseY) / treeCanvas.scale
                    
                    // 根据滚轮方向调整缩放
                    var delta = wheel.angleDelta.y / 120  // 通常每次滚动为120的倍数
                    var scaleFactor = delta > 0 ? 1.1 : 0.9  // 向上放大，向下缩小
                    
                    var oldScale = treeCanvas.scale
                    var newScale = oldScale * scaleFactor
                    
                    // 限制缩放范围：0.3x 到 3x
                    if (newScale >= 0.3 && newScale <= 3.0) {
                        treeCanvas.scale = newScale
                        
                        // 缩放后，计算Canvas上同一个点在新缩放下的位置
                        var newCanvasPointX = canvasX * newScale
                        var newCanvasPointY = canvasY * newScale
                        
                        // 调整滚动位置，使Canvas上那个点仍然在鼠标位置
                        flickable.contentX = newCanvasPointX - mouseX
                        flickable.contentY = newCanvasPointY - mouseY
                        
                        // 显示缩放指示器
                        zoomIndicatorTimer.restart()
                    }
                    
                    wheel.accepted = true
                } else {
                    // 没按Ctrl键，不处理，让Flickable正常滚动
                    wheel.accepted = false
                }
            }
        }
        
        // 移动端：双指缩放功能（类似高德地图）
        PinchArea {
            anchors.fill: parent
            enabled: true
            
            property real initialScale: 1.0
            property real initialContentX: 0
            property real initialContentY: 0
            property point pinchCenter: Qt.point(0, 0)
            property point initialCanvasPoint: Qt.point(0, 0)
            
            onPinchStarted: function(pinch) {
                // 记录初始状态
                initialScale = treeCanvas.scale
                initialContentX = flickable.contentX
                initialContentY = flickable.contentY
                
                // 计算缩放中心点（双指中心）
                pinchCenter = pinch.center
                
                // 计算缩放中心在Canvas上的原始坐标
                initialCanvasPoint.x = (initialContentX + pinchCenter.x) / initialScale
                initialCanvasPoint.y = (initialContentY + pinchCenter.y) / initialScale
            }
            
            onPinchUpdated: function(pinch) {
                // 计算新的缩放值
                var newScale = initialScale * pinch.scale
                
                // 限制缩放范围：0.3x 到 3x
                newScale = Math.max(0.3, Math.min(3.0, newScale))
                
                treeCanvas.scale = newScale
                
                // 缩放后，调整滚动位置使缩放中心保持不变
                var newCanvasPointX = initialCanvasPoint.x * newScale
                var newCanvasPointY = initialCanvasPoint.y * newScale
                
                flickable.contentX = newCanvasPointX - pinchCenter.x
                flickable.contentY = newCanvasPointY - pinchCenter.y
                
                // 显示缩放指示器
                zoomIndicatorTimer.restart()
            }
            
            onPinchFinished: {
                // 缩放结束，无需额外操作
            }
            
            // 让单指触摸事件穿透，用于拖动
            MouseArea {
                anchors.fill: parent
                propagateComposedEvents: true
                onPressed: function(mouse) {
                    mouse.accepted = false
                }
            }
        }
        
        // 滚动区域监控
        
        // 垂直滚动条
        ScrollBar.vertical: ScrollBar {
            policy: ScrollBar.AlwaysOn
            minimumSize: 0.1
        }
        
        // 水平滚动条
        ScrollBar.horizontal: ScrollBar {
            policy: ScrollBar.AlwaysOn
            minimumSize: 0.1
        }

        Canvas {
            id: treeCanvas
            
            // 缩放属性
            property real scale: 1.0
            
            // 缩放平滑动画
            Behavior on scale {
                NumberAnimation {
                    duration: 200
                    easing.type: Easing.OutQuad
                }
            }
            
            // 应用缩放变换
            transform: Scale {
                origin.x: 0
                origin.y: 0
                xScale: treeCanvas.scale
                yScale: treeCanvas.scale
            }
            
            // 计算X坐标偏移量，使所有节点向右平移到Canvas可见区域
            property int xOffset: {
                if (skillModel.count === 0) return 0
                var minX = 999999
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    minX = Math.min(minX, skill.x)
                }
                // 确保最小X坐标至少为200（留出左侧边距）
                return minX < 200 ? 200 - minX : 0
            }
            
            // 计算Y坐标偏移量，使所有节点向下平移到Canvas可见区域
            property int yOffset: {
                if (skillModel.count === 0) return 0
                var minY = 999999
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    minY = Math.min(minY, skill.y)
                }
                // 确保最小Y坐标至少为200（留出顶部边距）
                return minY < 200 ? 200 - minY : 0
            }
            
            // 动态计算Canvas宽度，确保包含所有技能节点
            width: {
                if (skillModel.count === 0) return 2000
                
                var maxX = -999999
                var minX = 999999
                
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    maxX = Math.max(maxX, skill.x + 60) // 60是技能节点宽度
                    minX = Math.min(minX, skill.x)
                }
                
                // 计算X偏移量
                var offsetX = minX < 200 ? 200 - minX : 0
                
                // 应用偏移后的最大X坐标（最右侧节点的右边缘）
                var adjustedMaxX = maxX + offsetX
                
                // Canvas宽度 = 从0到最右侧节点 + 右侧边距
                // 确保右侧边距足够大，至少800px，避免节点被截断
                var rightMargin = 800
                var totalWidth = adjustedMaxX + rightMargin
                
                // 确保Canvas宽度足够大，不依赖flickable.width
                return Math.max(totalWidth, 2000)
            }
            
            height: {
                if (skillModel.count === 0) return 3000
                
                var maxY = -999999
                var minY = 999999
                
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    maxY = Math.max(maxY, skill.y + 60) // 60是技能节点高度
                    minY = Math.min(minY, skill.y)
                }
                
                // 计算Y偏移量
                var offsetY = minY < 200 ? 200 - minY : 0
                
                // 应用偏移后的最大Y坐标（底部节点的底部边缘）
                var adjustedMaxY = maxY + offsetY
                
                // Canvas高度 = 从0到最底部节点 + 底部边距
                var totalHeight = adjustedMaxY + 200
                
                return Math.max(totalHeight, flickable.height + 500)
            }
            
            // Canvas高度变化监控
            
            // 监听技能模型变化，动态调整Canvas尺寸和重绘连线
            Connections {
                target: skillModel
                function onCountChanged() {
                    // 立即更新Canvas尺寸，确保模型数据已更新
                    updateCanvasSizeTimer.restart()
                    // 节点数量变化时重绘连线
                    Qt.callLater(function() {
                        treeCanvas.requestPaint()
                    })
                }
                function onDataChanged() {
                    // 数据变化时也更新Canvas尺寸
                    updateCanvasSizeTimer.restart()
                    Qt.callLater(function() {
                        treeCanvas.requestPaint()
                    })
                }
            }
            
            // 定时器用于延迟更新Canvas尺寸
            Timer {
                id: updateCanvasSizeTimer
                interval: 50  // 从100减少到50ms，更快响应
                repeat: false
                onTriggered: {
                    // 强制重新计算Canvas尺寸 - 通过改变绑定来触发
                    var tempCount = skillModel.count
                    
                    // 记录当前滚动位置
                    var oldContentX = flickable.contentX
                    var oldContentY = flickable.contentY
                    
                    // 触发width和height的重新计算
                    treeCanvas.width = treeCanvas.width
                    treeCanvas.height = treeCanvas.height
                    
                    // 恢复滚动位置（如果Canvas变大了）
                    flickable.contentX = oldContentX
                    flickable.contentY = oldContentY
                    
                    treeCanvas.requestPaint()
                }
            }

            onPaint: {
                var ctx = getContext("2d")
                ctx.clearRect(0, 0, width, height)
                
                // 绘制背景
                ctx.fillStyle = "#FFF0F5"
                ctx.fillRect(0, 0, width, height)
                
                // 绘制技能节点之间的连线（使用贝塞尔曲线）
                ctx.lineWidth = 3
                ctx.lineCap = "round"
                ctx.lineJoin = "round"
                
                // 用于给不同父节点的连线分配颜色
                var parentColors = {}
                var colorPalette = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E2"]
                var colorIndex = 0
                
                for (var i = 0; i < skillModel.count; i++) {
                    var skill = skillModel.get(i)
                    
                    // 只绘制有父节点的技能的连线
                    if (skill.parent !== -1) {
                        // 找到对应的父技能
                        var parentFound = false
                        for (var j = 0; j < skillModel.count; j++) {
                            var parentSkill = skillModel.get(j)
                            
                            // 关键：只有当节点的parent字段等于父节点的id时才绘制连线
                            if (parentSkill.id === skill.parent) {
                                parentFound = true
                                
                                // 为每个父节点分配固定颜色
                                if (!(parentSkill.id in parentColors)) {
                                    parentColors[parentSkill.id] = colorPalette[colorIndex % colorPalette.length]
                                    colorIndex++
                                }
                                ctx.strokeStyle = parentColors[parentSkill.id]
                                
                                // 计算连线的起点和终点（应用X和Y偏移）
                                // 父节点：圆圈顶部中心点 (节点是60x60，半径30，顶部在y位置)
                                var startX = parentSkill.x + xOffset + 30 // 父技能X中心
                                var startY = parentSkill.y + yOffset // 父技能圆圈顶部
                                // 子节点：圆圈底部中心点 (底部在y+60位置)
                                var endX = skill.x + xOffset + 30 // 子技能X中心
                                var endY = skill.y + yOffset + 60 // 子技能圆圈底部
                                
                                // 绘制贝塞尔曲线
                                ctx.beginPath()
                                ctx.moveTo(startX, startY)
                                
                                // 计算控制点，创建优美的S形曲线
                                // 从父节点顶部（startY）到子节点底部（endY，endY > startY因为子节点在上方，Y坐标小）
                                var deltaY = endY - startY
                                var controlY1 = startY + deltaY * 0.3
                                var controlY2 = startY + deltaY * 0.7
                                
                                // 使用三次贝塞尔曲线
                                ctx.bezierCurveTo(
                                    startX, controlY1,      // 第一个控制点
                                    endX, controlY2,        // 第二个控制点
                                    endX, endY              // 终点
                                )
                                
                                ctx.stroke()
                                break // 找到父节点后立即退出循环
                            }
                        }
                        
                        // 如果没找到父节点，跳过
                        if (!parentFound) {
                            // 父节点未找到
                        }
                    }
                }
            }
            
            // 右键菜单 - 捕获空白区域的右键点击
            MouseArea {
                anchors.fill: parent
                acceptedButtons: Qt.RightButton
                z: -1  // 放在节点下面，避免拦截节点的点击事件
                
                onClicked: function(mouse) {
                    // 检查是否点击在节点上
                    var clickedOnNode = false
                    for (var i = 0; i < skillModel.count; i++) {
                        var skill = skillModel.get(i)
                        var nodeX = skill.x + treeCanvas.xOffset
                        var nodeY = skill.y + treeCanvas.yOffset
                        var dx = mouse.x - (nodeX + 30)  // 30是节点半径
                        var dy = mouse.y - (nodeY + 30)
                        var distance = Math.sqrt(dx*dx + dy*dy)
                        
                        if (distance < 30) {  // 30是节点半径
                            clickedOnNode = true
                            break
                        }
                    }
                    
                    // 如果没有点击在节点上，显示创建根节点菜单
                    if (!clickedOnNode) {
                        contextMenu.x = mouse.x
                        contextMenu.y = mouse.y
                        contextMenu.open()
                    }
                }
            }

            // 技能节点 Repeater
            Repeater {
                model: skillModel // QAbstractListModel 暴露为 skillModel
                
                // Repeater组件
                
                // 当模型数据变化时，重新绘制Canvas
                onModelChanged: {
                    treeCanvas.requestPaint()
                }

                delegate: Rectangle {
                    id: skillNode
                    // 使用模型数据中的 x, y 坐标（应用X和Y偏移）
                    x: model.x + treeCanvas.xOffset
                    y: model.y + treeCanvas.yOffset
                    width: 60
                    height: 60
                    radius: 30
                    
                    // 添加平滑的位置过渡动画
                    Behavior on x {
                        enabled: !deleteMode  // 删除模式下禁用，避免和抖动动画冲突
                        NumberAnimation {
                            duration: 500
                            easing.type: Easing.OutCubic
                        }
                    }
                    
                    Behavior on y {
                        enabled: !deleteMode  // 删除模式下禁用
                        NumberAnimation {
                            duration: 500
                            easing.type: Easing.OutCubic
                        }
                    }
                    
                    // 删除模式下的抖动动画
                    SequentialAnimation on x {
                        running: deleteMode
                        loops: Animation.Infinite
                        NumberAnimation { to: model.x + treeCanvas.xOffset - 5; duration: 100 }
                        NumberAnimation { to: model.x + treeCanvas.xOffset + 5; duration: 100 }
                        NumberAnimation { to: model.x + treeCanvas.xOffset; duration: 100 }
                    }
                    
                    // 新的颜色方案：已完成=绿色（优先级最高），未完成=灰色，选中=淡金色
                    // 直接使用model属性，确保数据变化时自动更新
                    color: {
                        if (model.completed) return "#4CAF50"  // 绿色表示已完成（优先级最高）
                        else if (model.selected) return "#FFE082"  // 淡金色表示选中的当前节点
                        else return "#CCCCCC"  // 灰色表示未完成
                    }
                    border.color: {
                        if (model.completed) return "#2E7D32"  // 深绿色边框表示已完成（优先级最高）
                        else if (model.selected) return "#FFB300"  // 金色边框表示选中
                        else return "#999999"  // 深灰色边框表示未完成
                    }
                    border.width: 3
                    
                    // 添加颜色过渡动画
                    Behavior on color {
                        ColorAnimation { duration: 300 }
                    }
                    Behavior on border.color {
                        ColorAnimation { duration: 300 }
                    }

                    Text {
                        text: model.name
                        color: {
                            if (model.completed) return "white"  // 已完成（绿色背景）用白色文字
                            else return "#333333"  // 未完成和选中用深灰色文字
                        }
                        font.pixelSize: 12
                        font.bold: true
                        wrapMode: Text.Wrap
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                        anchors.centerIn: parent
                        width: parent.width - 10
                    }
                    
                    Item {
                        anchors.bottom: parent.bottom
                        anchors.right: parent.right
                        anchors.margins: -6
                        width: 28
                        height: 28
                        visible: model.isLevel && model.medalIcon && model.medalIcon !== ""
                        z: 11
                        
                        property bool isImage: typeof model.medalIcon === "string" &&
                                               (model.medalIcon.startsWith("qrc:") || model.medalIcon.startsWith("file:"))
                        
                        Rectangle {
                            anchors.fill: parent
                            radius: width / 2
                            color: "#FFFFFFEE"
                            border.color: "#FFB300"
                            border.width: 2
                        }
                        
                        Text {
                            anchors.centerIn: parent
                            text: parent.isImage ? "" : model.medalIcon
                            visible: !parent.isImage
                            font.pixelSize: 18
                        }
                        
                        Image {
                            anchors.fill: parent
                            anchors.margins: 3
                            source: parent.isImage ? model.medalIcon : ""
                            visible: parent.isImage
                            fillMode: Image.PreserveAspectFit
                        }
                    }
                    
                    Rectangle {
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.bottom: parent.bottom
                        anchors.bottomMargin: -6
                        width: parent.width - 12
                        height: 18
                        radius: 9
                        color: "#FFF8E1"
                        border.color: "#FFB300"
                        border.width: 1
                        visible: model.isLevel
                        opacity: 0.95
                        
                        Text {
                            anchors.centerIn: parent
                            text: "关卡"
                            color: "#FF6F00"
                            font.pixelSize: 12
                            font.bold: true
                        }
                    }
                    
                    // 星级显示（右上角）
                    Row {
                        anchors.top: parent.top
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.topMargin: -8  // 向上偏移到节点外
                        spacing: 1
                        visible: model.completed && model.starRating > 0
                        
                        Repeater {
                            model: parent.visible ? skillNode.getStarRating() : 0
                            
                            Text {
                                text: "⭐"
                                font.pixelSize: 14  // 小一点的星星
                                scale: 0.8
                                
                                // 星星闪烁动画（可选）
                                SequentialAnimation on scale {
                                    loops: Animation.Infinite
                                    running: parent.parent.visible
                                    NumberAnimation { to: 0.9; duration: 800 }
                                    NumberAnimation { to: 0.8; duration: 800 }
                                }
                            }
                        }
                    }
                    
                    // 获取星级的辅助函数
                    function getStarRating() {
                        return model.starRating
                    }
                    
                    // 删除模式下的减号按钮（相对定位，固定在节点右上角）
                    Rectangle {
                        anchors.top: parent.top
                        anchors.right: parent.right
                        anchors.margins: 5
                        width: 25
                        height: 25
                        radius: 12.5
                        color: "#FF4444"
                        visible: deleteMode
                        z: 10  // 确保在最上层
                        
                        Text {
                            anchors.centerIn: parent
                            text: "−"
                            color: "white"
                            font.pixelSize: 18
                            font.bold: true
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                // 直接显示删除确认对话框
                                // 在C++的deleteSkill中会检查：有子节点的根节点无法删除
                                showDeleteConfirmDialog(model.id, model.name)
                            }
                            // 阻止事件冒泡到父级MouseArea
                            propagateComposedEvents: false
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        
                        // 单击：选中节点（Windows和Android都一样）
                        onClicked: {
                            // 在删除模式下，不响应点击事件
                            if (deleteMode) {
                                return
                            }
                            // 单击选中技能（节点变黄色）
                            skillModel.selectSkill(model.id)
                        }
                        
                        // 双击：显示操作菜单（仅Windows）
                        onDoubleClicked: {
                            // 在删除模式下，不响应双击事件
                            if (deleteMode) {
                                return
                            }
                            // 仅在非Android平台响应双击
                            if (Qt.platform.os !== "android") {
                                // 显示操作菜单
                                    showSkillActionDialog(model.id, model.name, model.completed, model.isLevel)
                            }
                        }
                        
                        // 长按：显示操作菜单（仅Android）
                        onPressAndHold: {
                            // 在删除模式下，不响应长按事件
                            if (deleteMode) {
                                return
                            }
                            // 仅在Android平台响应长按
                            if (Qt.platform.os === "android") {
                                // 显示操作菜单
                                showSkillActionDialog(model.id, model.name, model.completed, model.isLevel)
                            }
                        }
                    }
                    
                    // 双击编辑名称
                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.RightButton
                        onClicked: function(mouse) {
                            if (mouse.button === Qt.RightButton) {
                                showEditDialog(model.id, model.name)
                            }
                        }
                    }

                    // 动画效果
                    states: State {
                        name: "unlocked"
                        when: model.unlocked
                        PropertyChanges { target: parent; scale: 1.1 }
                    }

                    transitions: Transition {
                        from: ""; to: "unlocked"
                        NumberAnimation { properties: "scale"; duration: 300; easing.type: Easing.OutBounce }
                    }
                }
            }
        }

        // Timer 用于定期重绘 Canvas，确保连接线跟随节点变化
        Timer {
            interval: 200
            running: true
            repeat: true
            onTriggered: treeCanvas.requestPaint()
        }
    }
    
    // 根据难度返回表情符号
    function getDifficultyEmoji(difficulty) {
        switch(difficulty) {
            case 1: return "⭐"
            case 2: return "⭐⭐"
            case 3: return "⭐⭐⭐"
            case 4: return "⭐⭐⭐⭐"
            case 5: return "⭐⭐⭐⭐⭐"
            default: return "⭐"
        }
    }
    
    // 显示技能详情
    function showSkillDetails(skillId) {
        // 这里可以添加技能详情对话框
    }
    
    // 显示完成确认对话框
    function showStarRatingDialog(skillId, skillName) {
        starRatingDialog.skillId = skillId
        starRatingDialog.skillName = skillName
        starRatingDialog.maxStars = Math.max(1, skillModel.getSkillMaxStarRating(skillId))
        starRatingDialog.open()
    }
    
    // 显示编辑对话框
    function showEditDialog(skillId, skillName) {
        editDialog.skillId = skillId
        editDialog.skillName = skillName
        editDialog.open()
    }
    
    // 显示编辑技能树对话框
    function showEditTreeDialog(treeId, treeName) {
        editTreeDialog.treeId = treeId
        editTreeDialog.treeName = treeName
        editTreeDialog.open()
    }
    
    // 显示技能操作对话框
    function showSkillActionDialog(skillId, skillName, isCompleted, isLevelNode) {
        skillActionDialog.skillId = skillId
        skillActionDialog.skillName = skillName
        skillActionDialog.isCompleted = isCompleted
        skillActionDialog.isLevel = !!isLevelNode
        skillActionDialog.open()
    }
    
    // 显示添加子技能对话框
    function showAddChildDialog(parentId) {
        addChildDialog.parentId = parentId
        addChildDialog.open()
    }

    function showAddLevelDialog(parentId) {
        addLevelDialog.parentId = parentId
        addLevelDialog.open()
    }
    
    // 停止所有抖动动画
    function stopAllShaking() {
        // 这里需要停止所有技能节点的抖动动画
        // 由于Repeater中的每个delegate都是独立的，我们需要通过信号来通知
        // 暂时留空，后续实现
    }
    
    // 删除技能节点
    function deleteSkill(skillId) {
        skillModel.deleteSkill(skillId)
    }
    
    // 显示删除确认对话框
    function showDeleteConfirmDialog(skillId, skillName) {
        deleteConfirmDialog.skillId = skillId
        deleteConfirmDialog.skillName = skillName
        deleteConfirmDialog.open()
    }
    
    // 显示删除技能树确认对话框
    function showDeleteTreeConfirmDialog(treeId, treeName) {
        deleteTreeConfirmDialog.treeId = treeId
        deleteTreeConfirmDialog.treeName = treeName
        deleteTreeConfirmDialog.open()
    }
    
    // 显示只剩一个技能树的警告对话框
    function showSingleTreeWarningDialog() {
        singleTreeWarningDialog.open()
    }
    
    // 删除技能树
    function deleteSkillTree(treeId) {
        skillModel.deleteSkillTree(treeId)
        // 刷新技能树列表
        treeSelector.model = skillModel.getSkillTrees()
    }
    
    // 三星评价对话框
    Dialog {
        id: starRatingDialog
        property int skillId: -1
        property string skillName: ""
        property int selectedStars: 0  // 当前选择的星星数量（1-5）
        property int maxStars: 3  // 星级上限（技能3星，关卡5星）
        
        title: "🎉 选择完成星级"
        anchors.centerIn: parent
        width: 400
        height: 350
        modal: true
        
        onOpened: {
            // 打开时重置为当前星级或默认3星
            selectedStars = 0
            if (maxStars < 1) {
                maxStars = 3
            }
            var currentStars = skillModel.getSkillStarRating(skillId)
            if (currentStars > 0) {
                selectedStars = Math.min(currentStars, maxStars)
            }
        }
        
        Column {
            anchors.fill: parent
            spacing: 25
            
            Text {
                text: "技能: " + starRatingDialog.skillName
                font.pixelSize: 18
                font.bold: true
                wrapMode: Text.WordWrap
                width: parent.width
                horizontalAlignment: Text.AlignHCenter
                color: "#2196F3"
            }
            
            Text {
                text: "选择你的完成星级："
                font.pixelSize: 16
                width: parent.width
                horizontalAlignment: Text.AlignHCenter
            }
            
            // 三星选择区域
            Row {
                id: starRow
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Repeater {
                    model: Math.max(1, starRatingDialog.maxStars)
                    
                    Rectangle {
                        width: 80
                        height: 80
                        color: "transparent"
                        
                        property int starIndex: index + 1
                        property bool isSelected: starRatingDialog.selectedStars >= starIndex
                        
                        // 星星文本
                        Text {
                            id: starText
                            anchors.centerIn: parent
                            text: parent.isSelected ? "⭐" : "☆"
                            font.pixelSize: 60
                            scale: parent.isSelected ? 1.0 : 0.8
                            
                            Behavior on scale {
                                NumberAnimation { duration: 200; easing.type: Easing.OutBack }
                            }
                        }
                        
                        // 点击区域
                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            cursorShape: Qt.PointingHandCursor
                            
                            onClicked: {
                                starRatingDialog.selectedStars = parent.starIndex
                                // 触发星星点亮动画
                                starAnimation.restart()
                            }
                            
                            onEntered: {
                                parent.scale = 1.15
                            }
                            
                            onExited: {
                                parent.scale = 1.0
                            }
                        }
                        
                        Behavior on scale {
                            NumberAnimation { duration: 150 }
                        }
                        
                        // 点亮动画
                        SequentialAnimation {
                            id: starAnimation
                            running: false
                            
                            ParallelAnimation {
                                NumberAnimation {
                                    target: starText
                                    property: "scale"
                                    to: 1.3
                                    duration: 150
                                }
                                NumberAnimation {
                                    target: starText
                                    property: "rotation"
                                    to: 20
                                    duration: 150
                                }
                            }
                            
                            ParallelAnimation {
                                NumberAnimation {
                                    target: starText
                                    property: "scale"
                                    to: 1.0
                                    duration: 150
                                }
                                NumberAnimation {
                                    target: starText
                                    property: "rotation"
                                    to: 0
                                    duration: 150
                                }
                            }
                        }
                    }
                }
            }
            
            // 星级说明
            Text {
                text: starRatingDialog.selectedStars > 0
                      ? "当前选择：" + starRatingDialog.selectedStars + " 星 / " + starRatingDialog.maxStars + " 星"
                      : "点击星星选择完成等级"
                font.pixelSize: 14
                width: parent.width
                horizontalAlignment: Text.AlignHCenter
                color: starRatingDialog.selectedStars > 0 ? "#4CAF50" : "#666666"
                wrapMode: Text.WordWrap
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "✅ 确认完成"
                    enabled: starRatingDialog.selectedStars > 0
                    font.pixelSize: 16
                    font.bold: true
                    
                    background: Rectangle {
                        color: parent.enabled ? (parent.pressed ? "#45a049" : "#4CAF50") : "#cccccc"
                        radius: 8
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        font: parent.font
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        if (starRatingDialog.selectedStars > 0) {
                            skillModel.completeSkillWithStars(starRatingDialog.skillId, starRatingDialog.selectedStars)
                            starRatingDialog.close()
                            starEffect.start()  // 触发完成特效
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    font.pixelSize: 16
                    
                    onClicked: starRatingDialog.close()
                }
            }
        }
    }
    
    // 编辑技能名称对话框
    Dialog {
        id: editDialog
        property int skillId: -1
        property string skillName: ""
        
        title: "编辑技能名称"
        anchors.centerIn: parent
        width: 300
        height: 150
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "修改技能名称："
                font.pixelSize: 14
                width: parent.width
            }
            
            TextField {
                id: skillNameField
                width: parent.width
                placeholderText: "请输入新的技能名称"
                text: editDialog.skillName
                
                // 回车键确认（PC端）
                Keys.onReturnPressed: {
                    if (skillNameField.text.trim() !== "") {
                        skillModel.updateSkillName(editDialog.skillId, skillNameField.text.trim())
                        editDialog.close()
                    }
                }
                
                // Enter键确认（小键盘）
                Keys.onEnterPressed: {
                    if (skillNameField.text.trim() !== "") {
                        skillModel.updateSkillName(editDialog.skillId, skillNameField.text.trim())
                        editDialog.close()
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "保存"
                    onClicked: {
                        if (skillNameField.text.trim() !== "") {
                            skillModel.updateSkillName(editDialog.skillId, skillNameField.text.trim())
                            editDialog.close()
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: editDialog.close()
                }
            }
        }
    }
    
    // 技能操作对话框 - Material Design 3 风格
    Dialog {
        id: skillActionDialog
        property int skillId: -1
        property string skillName: ""
        property bool isCompleted: false
        property bool isLevel: false
        
        anchors.centerIn: parent
        width: 360
        height: contentColumn.height
        modal: true
        padding: 0
        closePolicy: Dialog.CloseOnEscape | Dialog.CloseOnPressOutside
        
        // Material Design 3 背景
        background: Rectangle {
            color: "#FFFFFF"
            radius: 28
            border.width: 0
            
            // 阴影效果
            Rectangle {
                anchors.fill: parent
                anchors.margins: -2
                color: "transparent"
                radius: 30
                border.color: "#E0E0E0"
                border.width: 1
                z: -1
            }
        }
        
        // 内容区域
        Column {
            id: contentColumn
            width: parent.width
            spacing: 0
            
            // 标题栏
            Rectangle {
                width: parent.width
                height: 80
                color: "#F5F5F5"
                clip: true
                
                Rectangle {
                    anchors.fill: parent
                    color: parent.color
                    radius: 28
                }
                
                Row {
                    anchors.left: parent.left
                    anchors.leftMargin: 24
                    anchors.verticalCenter: parent.verticalCenter
                    spacing: 12
                    
                    Rectangle {
                        width: 40
                        height: 40
                        radius: 20
                        color: "#E3F2FD"
                        anchors.verticalCenter: parent.verticalCenter
                        
                        Text {
                            anchors.centerIn: parent
                            text: "🎯"
                            font.pixelSize: 20
                        }
                    }
                    
                    Column {
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 4
                        
                        Text {
                            text: "技能操作"
                            font.pixelSize: 20
                            font.bold: true
                            color: "#212121"
                        }
                        
                        Text {
                            text: skillActionDialog.skillName
                            font.pixelSize: 14
                            color: "#757575"
                            width: 240
                            elide: Text.ElideRight
                        }
                    }
                }
            }
            
            // 按钮列表区域
            Column {
                width: parent.width
                spacing: 0
                padding: 8
                bottomPadding: 8
                
                // 重命名按钮
                Rectangle {
                    width: parent.width - 16
                    height: 64
                    radius: 16
                    color: mouseArea1.containsMouse ? "#F5F5F5" : "transparent"
                    
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 16
                        
                        Text {
                            text: "✏️"
                            font.pixelSize: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: "重命名"
                            font.pixelSize: 16
                            color: "#212121"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    MouseArea {
                        id: mouseArea1
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            skillActionDialog.close()
                            showEditDialog(skillActionDialog.skillId, skillActionDialog.skillName)
                        }
                    }
                }
                
                // 生成子节点按钮
                Rectangle {
                    width: parent.width - 16
                    height: 64
                    radius: 16
                    color: mouseArea2.containsMouse ? "#F5F5F5" : "transparent"
                    
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 16
                        
                        Text {
                            text: "➕"
                            font.pixelSize: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: "生成子节点"
                            font.pixelSize: 16
                            color: "#212121"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    MouseArea {
                        id: mouseArea2
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            skillActionDialog.close()
                            Qt.callLater(function() {
                                showAddChildDialog(skillActionDialog.skillId)
                            })
                        }
                    }
                }

                // 增加关卡按钮
                Rectangle {
                    width: parent.width - 16
                    height: 64
                    radius: 16
                    visible: !skillActionDialog.isLevel
                    color: mouseAreaLevel.containsMouse ? "#F5F5F5" : "transparent"
                    
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 16
                        
                        Text {
                            text: "🕹️"
                            font.pixelSize: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: "增加关卡"
                            font.pixelSize: 16
                            color: "#512DA8"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    MouseArea {
                        id: mouseAreaLevel
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            skillActionDialog.close()
                            Qt.callLater(function() {
                                showAddLevelDialog(skillActionDialog.skillId)
                            })
                        }
                    }
                }
                
                // 完成/取消完成按钮
                Rectangle {
                    width: parent.width - 16
                    height: 64
                    radius: 16
                    color: mouseArea3.containsMouse ? "#F5F5F5" : "transparent"
                    
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 16
                        
                        Text {
                            text: skillActionDialog.isCompleted ? "↩️" : "✅"
                            font.pixelSize: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: skillActionDialog.isCompleted ? "取消完成" : "完成技能"
                            font.pixelSize: 16
                            color: skillActionDialog.isCompleted ? "#F44336" : "#4CAF50"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    MouseArea {
                        id: mouseArea3
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            skillActionDialog.close()
                            if (skillActionDialog.isCompleted) {
                                // 取消完成
                                skillModel.uncompleteSkill(skillActionDialog.skillId)
                                timerEffect.start()  // 触发计时器闪烁特效
                            } else {
                                // 完成技能 - 打开三星选择对话框
                                showStarRatingDialog(skillActionDialog.skillId, skillActionDialog.skillName)
                            }
                        }
                    }
                }
                
                // 重新挑战按钮（仅完成时显示）
                Rectangle {
                    width: parent.width - 16
                    height: 64
                    radius: 16
                    visible: skillActionDialog.isCompleted
                    color: mouseArea4.containsMouse ? "#F5F5F5" : "transparent"
                    
                    Row {
                        anchors.left: parent.left
                        anchors.leftMargin: 20
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: 16
                        
                        Text {
                            text: "🌟"
                            font.pixelSize: 24
                            anchors.verticalCenter: parent.verticalCenter
                        }
                        
                        Text {
                            text: "重新挑战"
                            font.pixelSize: 16
                            color: "#FF9800"
                            anchors.verticalCenter: parent.verticalCenter
                        }
                    }
                    
                    MouseArea {
                        id: mouseArea4
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        onClicked: {
                            skillActionDialog.close()
                            // 打开三星选择对话框，挑战更高星级
                            showStarRatingDialog(skillActionDialog.skillId, skillActionDialog.skillName)
                        }
                    }
                }
                
            }
        }
    }
    
    // 添加子技能对话框
    Dialog {
        id: addChildDialog
        property int parentId: -1
        
        title: "添加子技能"
        anchors.centerIn: parent
        width: 300
        height: 150
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "请输入子技能名称："
                font.pixelSize: 14
                width: parent.width
            }
            
            TextField {
                id: childNameField
                width: parent.width
                placeholderText: "请输入子技能名称"
                text: ""
                
                // 回车键确认（PC端）
                Keys.onReturnPressed: {
                    if (childNameField.text.trim() !== "") {
                        skillModel.addChildSkill(addChildDialog.parentId, childNameField.text.trim())
                        addChildDialog.close()
                        childNameField.text = ""  // 清空输入框
                    }
                }
                
                // Enter键确认（小键盘）
                Keys.onEnterPressed: {
                    if (childNameField.text.trim() !== "") {
                        skillModel.addChildSkill(addChildDialog.parentId, childNameField.text.trim())
                        addChildDialog.close()
                        childNameField.text = ""  // 清空输入框
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "添加"
                    onClicked: {
                        if (childNameField.text.trim() !== "") {
                            skillModel.addChildSkill(addChildDialog.parentId, childNameField.text.trim())
                            addChildDialog.close()
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: addChildDialog.close()
                }
            }
        }
    }

    // 添加关卡对话框
    Dialog {
        id: addLevelDialog
        property int parentId: -1
        property var medalOptions: []
        property string selectedMedalIcon: ""
        
        title: "增加关卡"
        anchors.centerIn: parent
        width: 360
        height: 420
        modal: true
        
        onOpened: {
            levelNameField.text = ""
            levelStarSpin.value = 3
            var icons = skillModel.getAvailableMedalIcons()
            if (icons && icons.length > 0) {
                medalOptions = icons
            } else {
                medalOptions = ["🏅", "🎖️", "👑", "🌟", "💎", "🚀", "🛡️", "🧠", "🎯", "⚡", "🧸", "🐋", "🐳", "🐬", "🧒", "🐒", "👹", "🐶", "🦸", "🐲", "👾", "🪐", "🌍", "☀️", "🌙", "🛸", "🛰️", "🐼", "🐧"]
            }
            selectedMedalIcon = medalOptions.length > 0 ? medalOptions[0] : "🏅"
            levelNameField.forceActiveFocus()
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 18
            
            Text {
                text: "请输入关卡名称："
                font.pixelSize: 14
                width: parent.width
            }
            
            TextField {
                id: levelNameField
                width: parent.width
                placeholderText: "例如：第1关：集合苹果"
                
                Keys.onReturnPressed: addLevelDialog.confirmLevel()
                Keys.onEnterPressed: addLevelDialog.confirmLevel()
            }
            
            Row {
                spacing: 10
                anchors.horizontalCenter: parent.horizontalCenter
                
                Text {
                    text: "星星上限："
                    font.pixelSize: 14
                    anchors.verticalCenter: parent.verticalCenter
                }
                
                SpinBox {
                    id: levelStarSpin
                    from: 1
                    to: 5
                    stepSize: 1
                    value: 3
                    editable: true
                }
            }
            
            Column {
                width: parent.width
                spacing: 10
                
                Text {
                    text: "选择勋章图标："
                    font.pixelSize: 14
                }
                
                GridView {
                    id: medalGrid
                    width: parent.width
                    height: 140
                    cellWidth: 56
                    cellHeight: 56
                    model: addLevelDialog.medalOptions
                    visible: count > 0
                    clip: true
                    
                    delegate: Rectangle {
                        width: 48
                        height: 48
                        radius: 16
                        property bool isImage: typeof modelData === "string" && (modelData.startsWith("qrc:") || modelData.startsWith("file:"))
                        color: addLevelDialog.selectedMedalIcon === modelData ? "#FFF8E1" : "white"
                        border.color: addLevelDialog.selectedMedalIcon === modelData ? "#FFB300" : "#DDDDDD"
                        border.width: 2
                        anchors.margins: 4
                        
                        Text {
                            anchors.centerIn: parent
                            text: parent.isImage ? "" : modelData
                            font.pixelSize: 26
                            visible: !parent.isImage
                        }
                        
                        Image {
                            anchors.fill: parent
                            anchors.margins: 6
                            source: parent.isImage ? modelData : ""
                            visible: parent.isImage
                            fillMode: Image.PreserveAspectFit
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: addLevelDialog.selectedMedalIcon = modelData
                        }
                    }
                }
                
                Row {
                    spacing: 10
                    anchors.horizontalCenter: parent.horizontalCenter
                    Text {
                        text: "已选："
                        font.pixelSize: 14
                        color: "#555555"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    Rectangle {
                        width: 48
                        height: 48
                        radius: 16
                        color: "#FFFFFF"
                        border.color: "#FFB300"
                        border.width: 2
                        visible: addLevelDialog.selectedMedalIcon !== ""
                        
                        property bool isImage: typeof addLevelDialog.selectedMedalIcon === "string" &&
                                               (addLevelDialog.selectedMedalIcon.startsWith("qrc:") || addLevelDialog.selectedMedalIcon.startsWith("file:"))
                        
                        Text {
                            anchors.centerIn: parent
                            text: parent.isImage ? "" : addLevelDialog.selectedMedalIcon
                            font.pixelSize: 26
                            visible: !parent.isImage
                        }
                        
                        Image {
                            anchors.fill: parent
                            anchors.margins: 6
                            source: parent.isImage ? addLevelDialog.selectedMedalIcon : ""
                            visible: parent.isImage
                            fillMode: Image.PreserveAspectFit
                        }
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "添加关卡"
                    onClicked: addLevelDialog.confirmLevel()
                }
                
                Button {
                    text: "取消"
                    onClicked: addLevelDialog.close()
                }
            }
        }
        
        function confirmLevel() {
            var name = levelNameField.text.trim()
            if (name !== "") {
                var icon = addLevelDialog.selectedMedalIcon && addLevelDialog.selectedMedalIcon !== "" ? addLevelDialog.selectedMedalIcon : "🏅"
                skillModel.addChildLevel(addLevelDialog.parentId, name, Math.round(levelStarSpin.value), icon)
                levelNameField.text = ""
                addLevelDialog.close()
            }
        }
    }
    
    // 删除确认对话框
    Dialog {
        id: deleteConfirmDialog
        property int skillId: -1
        property string skillName: ""
        
        title: "删除技能确认"
        anchors.centerIn: parent
        width: 350
        height: 200
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "确定要删除技能吗？"
                font.pixelSize: 16
                font.bold: true
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Text {
                text: "技能: " + deleteConfirmDialog.skillName
                font.pixelSize: 14
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Text {
                text: "⚠️ 删除后将同时删除所有子技能"
                font.pixelSize: 12
                color: "#FF4444"
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "确认删除"
                    background: Rectangle {
                        color: parent.pressed ? "#FF4444" : "#FF6666"
                        radius: 5
                    }
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    onClicked: {
                        deleteSkill(deleteConfirmDialog.skillId)
                        deleteConfirmDialog.close()
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: deleteConfirmDialog.close()
                }
            }
        }
    }
    
    // 编辑技能树名称对话框
    Dialog {
        id: editTreeDialog
        property string treeId: ""
        property string treeName: ""
        
        title: "编辑技能树名称"
        anchors.centerIn: parent
        width: 300
        height: 150
        modal: true
        
        // 对话框打开时设置初始值
        onOpened: {
            treeNameField.text = treeName
            treeNameField.selectAll()  // 选中所有文本，方便用户直接输入
            treeNameField.forceActiveFocus()  // 自动获得焦点
        }
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "修改技能树名称："
                font.pixelSize: 14
                width: parent.width
            }
            
            TextField {
                id: treeNameField
                width: parent.width
                placeholderText: "请输入新的技能树名称"
                
                // 回车键确认（PC端）
                Keys.onReturnPressed: {
                    if (treeNameField.text.trim() !== "") {
                        skillModel.updateSkillTreeName(editTreeDialog.treeId, treeNameField.text.trim())
                        // 刷新技能树列表
                        treeSelector.model = skillModel.getSkillTrees()
                        editTreeDialog.close()
                    }
                }
                
                // Enter键确认（小键盘）
                Keys.onEnterPressed: {
                    if (treeNameField.text.trim() !== "") {
                        skillModel.updateSkillTreeName(editTreeDialog.treeId, treeNameField.text.trim())
                        // 刷新技能树列表
                        treeSelector.model = skillModel.getSkillTrees()
                        editTreeDialog.close()
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "保存"
                    onClicked: {
                        if (treeNameField.text.trim() !== "") {
                            skillModel.updateSkillTreeName(editTreeDialog.treeId, treeNameField.text.trim())
                            // 刷新技能树列表
                            treeSelector.model = skillModel.getSkillTrees()
                            editTreeDialog.close()
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: editTreeDialog.close()
                }
            }
        }
    }
    
    // 删除技能树确认对话框
    Dialog {
        id: deleteTreeConfirmDialog
        property string treeId: ""
        property string treeName: ""
        
        title: "删除技能树确认"
        anchors.centerIn: parent
        width: 350
        height: 200
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "确定要删除整个技能树吗？"
                font.pixelSize: 16
                font.bold: true
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Text {
                text: "技能树: " + deleteTreeConfirmDialog.treeName
                font.pixelSize: 14
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Text {
                text: "⚠️ 删除后将无法恢复，所有技能节点都会被删除！"
                font.pixelSize: 12
                color: "#FF4444"
                width: parent.width
                wrapMode: Text.WordWrap
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                Button {
                    text: "确认删除"
                    background: Rectangle {
                        color: parent.pressed ? "#CC0000" : "#FF3333"
                        radius: 5
                    }
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    onClicked: {
                        deleteSkillTree(deleteTreeConfirmDialog.treeId)
                        deleteTreeConfirmDialog.close()
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: deleteTreeConfirmDialog.close()
                }
            }
        }
    }
    
    // 只剩一个技能树的警告对话框
    Dialog {
        id: singleTreeWarningDialog
        
        title: "无法删除"
        anchors.centerIn: parent
        width: 300
        height: 150
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "⚠️ 至少需要保留一个技能树！"
                font.pixelSize: 16
                font.bold: true
                color: "#FF4444"
                width: parent.width
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            Button {
                text: "确定"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: singleTreeWarningDialog.close()
            }
        }
    }
    
    // 奥特曼特效 - 入场动画
    SequentialAnimation {
        id: starEffect
        running: false
        
        // 步骤1: 奥特曼出现动画
        ParallelAnimation {
            NumberAnimation {
                target: aotermanEffect
                property: "opacity"
                from: 0
                to: 1
                duration: 300
            }
            
            NumberAnimation {
                target: aotermanEffect
                property: "scale"
                from: 0.5
                to: 1.5
                duration: 500
                easing.type: Easing.OutBounce
            }
        }
        
        // 步骤2: 开始播放gif
        ScriptAction {
            script: {
                aotermanEffect.playing = true
                aotermanEffect.currentFrame = 0  // 从第一帧开始
            }
        }
    }
    
    // 奥特曼消失动画
    SequentialAnimation {
        id: aotermanDisappearEffect
        running: false
        
        // 先停止gif播放，保持静止
        ScriptAction {
            script: {
                aotermanEffect.playing = false
            }
        }
        
        // 停留1.5秒
        PauseAnimation {
            duration: 1500
        }
        
        // 缩小并消失
        ParallelAnimation {
            NumberAnimation {
                target: aotermanEffect
                property: "opacity"
                from: 1
                to: 0
                duration: 500
            }
            
            NumberAnimation {
                target: aotermanEffect
                property: "scale"
                from: 1.5
                to: 0.5
                duration: 500
            }
        }
    }
    
    // 奥特曼gif特效
    AnimatedImage {
        id: aotermanEffect
        width: 200
        height: 200
        source: "qrc:/images/aoterman.gif"
        opacity: 0
        scale: 0
        anchors.centerIn: parent
        fillMode: Image.PreserveAspectFit
        z: 999  // 确保在最上层显示
        playing: false
        
        // 监听当前帧变化，播放完一遍后触发消失动画
        property bool hasCompletedOneCycle: false
        
        onCurrentFrameChanged: {
            // 当播放到最后一帧时，表示播放完一遍
            if (playing && currentFrame === frameCount - 1 && !hasCompletedOneCycle) {
                hasCompletedOneCycle = true
                aotermanDisappearEffect.start()
            }
        }
        
        // 重置标志
        onOpacityChanged: {
            if (opacity === 0) {
                hasCompletedOneCycle = false
            }
        }
    }
    
    // 计时器闪烁特效 - 入场动画（取消完成时使用）
    SequentialAnimation {
        id: timerEffect
        running: false
        
        // 步骤1: 计时器出现动画
        ParallelAnimation {
            NumberAnimation {
                target: timerEffectImage
                property: "opacity"
                from: 0
                to: 1
                duration: 300
            }
            
            NumberAnimation {
                target: timerEffectImage
                property: "scale"
                from: 0.5
                to: 1.5
                duration: 500
                easing.type: Easing.OutBounce
            }
        }
        
        // 步骤2: 开始播放gif
        ScriptAction {
            script: {
                timerEffectImage.playing = true
                timerEffectImage.currentFrame = 0  // 从第一帧开始
            }
        }
    }
    
    // 计时器消失动画
    SequentialAnimation {
        id: timerDisappearEffect
        running: false
        
        // 先停止gif播放，保持静止
        ScriptAction {
            script: {
                timerEffectImage.playing = false
            }
        }
        
        // 停留1.5秒
        PauseAnimation {
            duration: 1500
        }
        
        // 缩小并消失
        ParallelAnimation {
            NumberAnimation {
                target: timerEffectImage
                property: "opacity"
                from: 1
                to: 0
                duration: 500
            }
            
            NumberAnimation {
                target: timerEffectImage
                property: "scale"
                from: 1.5
                to: 0.5
                duration: 500
            }
        }
    }
    
    // 计时器闪烁gif特效
    AnimatedImage {
        id: timerEffectImage
        width: 200
        height: 200
        source: "qrc:/images/ultraman_timer.gif"
        opacity: 0
        scale: 0
        anchors.centerIn: parent
        fillMode: Image.PreserveAspectFit
        z: 999  // 确保在最上层显示
        playing: false
        
        // 监听当前帧变化，播放完一遍后触发消失动画
        property bool hasCompletedOneCycle: false
        
        onCurrentFrameChanged: {
            // 当播放到最后一帧时，表示播放完一遍
            if (playing && currentFrame === frameCount - 1 && !hasCompletedOneCycle) {
                hasCompletedOneCycle = true
                timerDisappearEffect.start()
            }
        }
        
        // 重置标志
        onOpacityChanged: {
            if (opacity === 0) {
                hasCompletedOneCycle = false
            }
        }
    }
    
    // 错误提示对话框
    Dialog {
        id: errorDialog
        property string errorMessage: ""
        
        title: "⚠️ 操作失败"
        anchors.centerIn: parent
        width: 400
        height: 200
        modal: true
        
        background: Rectangle {
            color: "#FFF3E0"
            radius: 10
            border.color: "#FF9800"
            border.width: 2
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: errorDialog.errorMessage
                font.pixelSize: 14
                color: "#E65100"
                wrapMode: Text.WordWrap
                width: parent.width
            }
            
            Button {
                text: "确定"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: errorDialog.close()
            }
        }
    }
    
    // 监听syncFailed信号来显示错误
    Connections {
        target: skillModel
        function onSyncFailed(errorMsg) {
            // 处理所有错误：添加节点、删除节点等
            errorDialog.errorMessage = errorMsg
            errorDialog.open()
        }
    }
    
    // 右键菜单
    Menu {
        id: contextMenu
        
        MenuItem {
            text: "🌳 创建新的根节点"
            onTriggered: {
                createRootNodeDialog.open()
            }
        }
    }
    
    // 创建根节点对话框
    Dialog {
        id: createRootNodeDialog
        
        title: "创建根节点"
        anchors.centerIn: parent
        width: 350
        height: 180
        modal: true
        
        background: Rectangle {
            color: "#F0F8FF"
            radius: 10
            border.color: "#4CAF50"
            border.width: 2
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: "请输入根节点名称："
                font.pixelSize: 14
                width: parent.width
            }
            
            TextField {
                id: rootNodeNameField
                width: parent.width
                placeholderText: "例如：数学技能树"
                focus: true
                
                Keys.onReturnPressed: {
                    if (rootNodeNameField.text.trim() !== "") {
                        skillModel.addSkill(rootNodeNameField.text.trim(), -1, "", "根节点", 1)
                        createRootNodeDialog.close()
                        rootNodeNameField.text = ""
                    }
                }
                
                Keys.onEnterPressed: {
                    if (rootNodeNameField.text.trim() !== "") {
                        skillModel.addSkill(rootNodeNameField.text.trim(), -1, "", "根节点", 1)
                        createRootNodeDialog.close()
                        rootNodeNameField.text = ""
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "创建"
                    
                    background: Rectangle {
                        radius: 20
                        color: parent.pressed ? "#45a049" : "#4CAF50"
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font.pixelSize: 14
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        if (rootNodeNameField.text.trim() !== "") {
                            skillModel.addSkill(rootNodeNameField.text.trim(), -1, "", "根节点", 1)
                            createRootNodeDialog.close()
                            rootNodeNameField.text = ""
                        }
                    }
                }
                
                Button {
                    text: "取消"
                    onClicked: {
                        createRootNodeDialog.close()
                        rootNodeNameField.text = ""
                    }
                }
            }
        }
    }
}
